import { getDetail, rightsConsume } from "@/api/modules/library";
import { addPay } from "@/api/modules/preview";
import { addOrderAndPay } from "@/api/modules/career.js";
import CryptoJS from "crypto-js";
import { extractParams } from "@/utils/handle.js";
export default {
  data() {
    return {
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      companyId: uni.getStorageSync("company-id"),
      id: "",
      recommendActivityList: [],
      showPopup: false,
      activity: {
        activitySubRel: { isFree: "1", previewImgList: [] },
      },
      buyStatus: false,
      activityRightVo: "",
      userInfo: null,
      paying: false,
      provider: "",
      loaded: false,
      isPC: false,
      preImg: this.$imgBaseSelf + "report/pre-img.png",
    };
  },
  computed: {
    status() {
      console.log("status", this.positionId);

      if (this.positionId && this.positionId.length > 0) {
        // 职神籍里的案例报告
        console.log("是之神级进入的案例报告");

        return -1;
      }
      if (this.activityRightVo.yltLevel == 0) {
        // 非一览通会员
        return 0;
      } else if (this.activityRightVo.yltLevel == 1) {
        // 初级会员
        return 1;
      } else if (this.activityRightVo.limitRightNumber > 0) {
        // 一览通（有权益数）
        return 2;
      } else if (
        this.activityRightVo.yltLevel == 4 &&
        this.activityRightVo.limitRightNumber < 1
      ) {
        // 一览通旗舰版（无权益数） 最高级
        return 3;
      } else if (this.activityRightVo.limitRightNumber < 1) {
        // 一览通标准版（无权益数）
        return 4;
      }
      //  else if (
      //   this.activityRightVo.yltLevel == 3 &&
      //   this.activityRightVo.limitRightNumber > 0
      // ) {
      //   // 一览通专业版（有权益数）
      //   return 4;
      // } else if (
      //   this.activityRightVo.yltLevel == 3 &&
      //   this.activityRightVo.limitRightNumber < 1
      // ) {
      //   // 一览通专业版（无权益数）
      //   return 5;
      // } else if (
      //   this.activityRightVo.yltLevel == 4 &&
      //   this.activityRightVo.limitRightNumber > 0
      // ) {
      //   // 一览通旗舰版（有权益数）
      //   return 5;
      // } else if (
      //   this.activityRightVo.yltLevel == 4 &&
      //   this.activityRightVo.limitRightNumber < 1
      // ) {
      //   // 一览通旗舰版（无权益数）
      //   return 5;
      // }
    },
    isShowPre() {
      return !this.buyStatus && !this.activityRightVo.rightBuyStatus;
    },
    isBuy() {
      return this.buyStatus || this.activityRightVo.rightBuyStatus;
    },
    formattedDate: function () {
      var today = new Date(); //获取当前时间
      var month = (today.getMonth() + 1).toString().padStart(2, "0"); //获取月份，不足两位的前面补0
      var year = today.getFullYear().toString().substr(0); //获取年份的后两位
      var day = today.getDate().toString().padStart(2, "0"); //获取天数，不足两位的前面补0
      return `${year}-${month}-${day}`; //拼接成mm-yy-dd的格式
    },
  },
  created() {
    this.userInfo = getApp().globalData.userInfo;
    if (this.personId && !this.userInfo.id) {
      this.$bus.$emit("getUserInfo", () => {
        this.userInfo = getApp().globalData.userInfo;
      });
    }
    uni.getProvider({
      service: "payment",
      success: (res) => {
        this.provider = res.provider;
      },
    });
  },
  onLoad(opt) {
    this.sourceFrom = opt.sourceFrom;
    this.positionId = opt.positionId || "";

    uni.getSystemInfo({
      success: (res) => {
        if (
          res.system.toLowerCase().includes("windows") ||
          res.system.toLowerCase().includes("macos") ||
          res.model.toLowerCase().includes("mac")
        ) {
          this.isPC = true;
        }
      },
    });
    if (opt.id) {
      this.id = opt.id;
    } else {
      const scene = decodeURIComponent(opt.scene);
      const params = extractParams(scene);
      let activityIdCode = params["id"] || "";
      this.id = activityIdCode;
    }
    console.log("reportCaseOpt-----", opt, this.id);
    if (!this.personId) {
      this.personId = "0";
    }
    this.getData();
  },
  methods: {
    handleDetail() {
      if (!this.loaded) return;
      if (this.buyStatus || this.activityRightVo.rightBuyStatus) {
        this.openReport();
      } else {
        this.showPopup = true;
      }
    },
    getData() {
      const params = {
        activityIdCode: this.id,
        personId: this.personId || "0",
        companyId: this.companyId,
        sourceFrom: this.sourceFrom,
      };
      uni.showLoading();
      return getDetail(params)
        .then((res) => {
          if (res.code == 200) {
            this.recommendActivityList = res.data.recommendActivityList;
            this.activity = res.data.activity;
            this.buyStatus = res.data.buyStatus;
            this.activityRightVo = res.data.activityRightVo;
            this.loaded = true;
            this.shareContent.contentTitle = this.activity.activityName;
            this.shareContent.contentType =
              this.showType == "report" ? "10" : "20";
            this.shareContent.contentId = this.id;
            this.setShareInfo && this.setShareInfo();
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "none",
            });
          }
          return res;
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    handleClick(item) {
      if (item.activityTypeCode == "CAREER_CASE") {
        uni.navigateTo({
          url: "/pagesSub/companyCenter/case/detail?id=" + item.activityIdCode,
        });
      } else if (item.activityTypeCode == "CAREER_REPORT") {
        uni.navigateTo({
          url:
            "/pagesSub/companyCenter/report/detail?id=" + item.activityIdCode,
        });
      }
    },
    openReport(fileUrl) {
      uni.showLoading({
        title: "打开中",
      });
      console.log(
        "fileUrl || this.activity.fileUrl",
        fileUrl || this.activity.fileUrl
      );

      uni.downloadFile({
        url: fileUrl || this.activity.fileUrl, // 文件的本身url
        filePath:
          wx.env.USER_DATA_PATH + "/" + this.activity.activityName + ".pdf", // 本地自定义的文件名
        success: function (res) {
          let filePath = res.filePath;
          uni.openDocument({
            filePath: filePath,
            success: function () {
              uni.hideLoading();
            },
            fail: function () {
              uni.hideLoading();
            },
          });
          uni.hideLoading();
        },
        fail: function (res) {
          uni.showLoading({
            title: res,
          });
        },
        complete: (res) => {
          console.log("complete", res);
        },
      });
    },
    handleUpdate() {
      this.showPopup = false;
      uni.navigateTo({
        url:
          "/pagesSub/companyCenter/vip/index?jumpLevel=" +
          (this.activityRightVo.yltLevel + 1),
      });
    },
    handleBuy() {
      if (this.provider.indexOf("wxpay") >= 0)
        this.goPay(this.activity.activityPrice);
    },
    goPay(price) {
      const openid = uni.getStorageSync("openid");
      if (this.positionId && this.positionId.length !== 0) {
        //职神籍里案例报告支付
        let params = {
          personId: uni.getStorageSync("person-id").slice(2) || "",
          openId: openid,
          productId: this.activity.activitySubRel.mallProductId,
          positionId: this.positionId,
          buyProductType: "20",
          activityId: this.activity.activityId,
        };
        uni.showLoading({
          title: "",
          mask: true,
        });
        addOrderAndPay(params)
          .then((res) => {
            if (res && res.code == 200) {
              this.requestPayment(res.data);
            } else {
              uni.hideLoading();
              this.paying = false;
              uni.showToast({
                title: res.status_desc,
                icon: "none",
              });
            }
          })
          .finally(() => {
            this.paying = false;
          });
      } else {
        //普通场景案例报告支付
        let params = {
          orderTypeCode: 20,
          orderFuncId: this.id,
          orderNum: price,
          orderUserId: this.userInfo.id,
          orderUserName:
            this.userInfo.iname || this.userInfo.uname || this.userInfo.id,
          orderCompanyId: this.userInfo.id,
          orderCompanyName:
            this.userInfo.iname || this.userInfo.uname || this.userInfo.id,
          channelType: 21,
          moduleType: "OCCUPATION_MODULE_TYPE",
          subject: this.activity.activityName,
          body:
            this.activity.activityIntroduce ||
            this.activity.activityDesc ||
            this.activity.activityName,
          openId: openid,
        };
        uni.showLoading({
          title: "",
          mask: true,
        });
        addPay(params, this.personId)
          .then((res) => {
            if (res && res.code == 200) {
              this.requestPayment(res.data);
            } else {
              uni.hideLoading();
              this.paying = false;
              uni.showToast({
                title: res.status_desc,
                icon: "none",
              });
            }
          })
          .finally(() => {
            this.paying = false;
          });
      }
    },
    // 支付
    requestPayment(data) {
      data.payData = JSON.parse(data.payData);
      uni.requestPayment({
        provider: this.provider[0],
        timeStamp: data.payData.timeStamp,
        nonceStr: data.payData.nonceStr,
        package: data.payData.package,
        signType: data.payData.signType,
        paySign: data.payData.paySign,
        success: (res) => {
          this.handlePaySuccess(res);
        },
        fail: (err) => {
          this.handlePayFial(err);
        },
      });
    },
    handlePaySuccess(res) {
      uni.hideLoading();
      uni.showToast({
        title: "支付成功",
        icon: "none",
      });
      this.showPopup = false;
      if (this.positionId) {
        let url =
          "/pagesSub/companyCenter/case/detail?id=" +
          this.activity.activityIdCode +
          "&&positionId=" +
          this.positionId +
          "&&isFromZhishenji=" +
          1 +
          "&&sourceFrom=" +
          this.encrypt("zhishenji" + this.formattedDate, "");
        uni.redirectTo({
          url,
        });
        return;
      }
      // this.getData().then((res) => {
      //   // this.openReport();
      // });
    },

    handlePayFial(err) {
      uni.hideLoading();
      let msg = "";
      if (err.errMsg == "requestPayment:fail cancel") {
        msg = "取消支付";
      } else {
        msg = err.errMsg;
      }
      uni.showToast({
        title: msg,
        icon: "none",
      });
    },
    //
    handleCheck() {
      this.rightsConsume();
    },
    // 权益消耗
    rightsConsume() {
      const params = {
        activityIdCode: this.id,
        companyId: this.companyId || this.personId,
        personId: this.personId,
      };
      uni.showLoading({
        title: "",
        mask: true,
      });
      rightsConsume(params)
        .then((res) => {
          if (res.code == 200) {
            this.getData().then((res) => {
              // this.openReport();
            });
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "none",
            });
          }
        })
        .finally(() => {
          this.showPopup = false;
          uni.hideLoading();
        });
    },
    handleFree() {
      this.showPopup = false;
      uni.navigateTo({
        url: "/pagesSub/companyCenter/vip/index",
      });
    },
    toPreview() {
      if (this.isPC) {
        uni.showToast({
          title: "报告预览暂不支持PC端设备，请前往移动端预览",
          icon: "none",
        });
        return;
      }
      if (!this.personId) {
        this.toLogin();
        return;
      }
      //打开pdf文件
      uni.showLoading({
        title: "加载中...",
      });
      if (
        this.activity.activitySubRel &&
        this.activity.activitySubRel.previewUrl
      ) {
        this.openReport(this.activity.activitySubRel.previewUrl);
      } else {
        uni.showToast({
          title: "暂无预览文件",
          icon: "none",
        });
      }
    },
    encrypt(word, keyStr) {
      // word, keyStr第一个参数是加密的字段名字  第二个是key值（16位）
      keyStr = keyStr || "*%&^%$&*()347845"; // 密文（密钥）
      var key = CryptoJS.enc.Utf8.parse(keyStr);
      var srcs = CryptoJS.enc.Utf8.parse(word);
      var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      });
      return encrypted.toString();
    },
  },
};
